#include "board_config.h"
#include "board_uart.h"
#include "platform.h"
#include "mpu9250.h"

extern TIM_HandleTypeDef trigger_tim_handler;
static volatile uint32_t systime_ms = 0;
extern struct event_queue event_queue;
extern SPI_HandleTypeDef spi1handler;
extern MPU9250_HandleTypeDef mpuHandler;

/**
 * @brief  Period elapsed callback in non blocking mode
 * @param  htim: TIM handle
 * @retval None
 */
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)
{
	if (htim == &trigger_tim_handler) {
		systime_ms++;
		board_stdout_flush();

		if (HAL_SPI_GetState(mpuHandler.spi) == HAL_SPI_STATE_READY) {
			mpu9250_nonblocking_process(&mpuHandler);
		}
	}
}

void HAL_SPI_TxRxCpltCallback(SPI_HandleTypeDef* hspi)
{
	if (hspi == &spi1handler) {
		mpuHandler.rx_handler((void *)&mpuHandler);
		spi_select(MPU9250_CS_PIN, 0);
	}
}

uint64_t board_get_systime()
{
	volatile uint32_t ms;
	uint32_t timer_cnt;

	do {
		ms = systime_ms;
		timer_cnt = trigger_tim_handler.Instance->CNT;
	} while(ms != systime_ms);

	return (uint64_t)ms*1000000/TRIGGER_FREQ + timer_cnt;
}

